package com.yami.shop.user.api.controller;

import com.yami.shop.bean.app.dto.ShopCartDto;
import com.yami.shop.bean.app.dto.ShopCartItemDto;
import com.yami.shop.bean.app.dto.ShopCartOrderMergerDto;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.enums.DeliveryType;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.vo.UserDeliveryInfoVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.CacheManagerUtil;
import com.yami.shop.delivery.api.manager.DeliveryOrderManager;
import com.yami.shop.manager.OrderUseScoreManager;
import com.yami.shop.manager.UserLevelOrderManager;
import com.yami.shop.manager.impl.ConfirmOrderManager;
import com.yami.shop.manager.impl.ShopCartAdapter;
import com.yami.shop.manager.impl.ShopCartItemAdapter;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.common.service.ScoreOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;


/**
 * @author LHD
 */
@RestController
@AllArgsConstructor
@RequestMapping("/p/score" )
@Tag(name = "积分商品订单接口")
public class ScoreOrderController {

    private final UserExtensionService userExtensionService;
    private final ProductService productService;
    private final ScoreOrderService scoreOrderService;
    private final CacheManagerUtil cacheManagerUtil;
    private final SkuService skuService;
    private final ShopCartAdapter shopCartAdapter;
    private final ShopCartItemAdapter shopCartItemAdapter;
    private final ConfirmOrderManager confirmOrderManager;
    private final DeliveryOrderManager deliveryOrderManager;
    private final UserLevelOrderManager userLevelOrderManager;
    private final OrderUseScoreManager orderUseScoreManager;

    @PostMapping("/confirm")
    @Operation(summary =  "结算，生成积分订单信息", description = "传入下单所需要的参数进行下单")
    public ServerResponseEntity<ShopCartOrderMergerDto> confirm(@Valid @RequestBody OrderParam orderParam) {
        if (Objects.isNull(orderParam.getOrderItem())) {
            // 请选择您需要的商品进行购买
            throw new YamiShopBindException("yami.score.select.num.shop");
        }
        String userId = SecurityUtils.getUser().getUserId();
        // 将要返回给前端的完整的订单信息
        ShopCartOrderMergerDto shopCartOrderMerger = new ShopCartOrderMergerDto();
        shopCartOrderMerger.setDvyType(DeliveryType.EXPRESS.getValue());
        shopCartOrderMerger.setOrderType(OrderType.SCORE);
        shopCartOrderMerger.setMold(0);
        shopCartOrderMerger.setIsScorePay(1);
        shopCartOrderMerger.setPreSellStatus(0);

        List<ShopCartItemDto> shopCartItemsDb = shopCartItemAdapter.getShopCartItem(orderParam.getOrderItem(), null, userId, orderParam.getAddrId());

        // 筛选过滤掉不同配送的商品
        List<ShopCartItemDto> shopCartItems = confirmOrderManager.filterShopItemsByType(shopCartOrderMerger, shopCartItemsDb);

        // 购物车
        List<ShopCartDto> shopCarts = shopCartAdapter.getShopCarts(shopCartItems);

        // 计算运费，获取用户地址，自提信息
        UserDeliveryInfoVO userDeliveryInfo = deliveryOrderManager.calculateAndGetDeliverInfo(userId, orderParam.getAddrId(), orderParam.getDvyType(), shopCartItems);

        // 当算完一遍店铺的各种满减活动时，重算一遍订单金额
        confirmOrderManager.recalculateAmountWhenFinishingCalculateShop(shopCartOrderMerger, shopCarts, userDeliveryInfo);

        double orderShopReduce = shopCartOrderMerger.getOrderReduce();

//        // 等级折扣
//        if (userLevelOrderManager != null) {
//            userLevelOrderManager.calculateLevelDiscount(shopCartOrderMerger);
//        }
//
//        // 结束平台优惠的计算之后，还要重算一遍金额
//        confirmOrderManager.recalculateAmountWhenFinishingCalculatePlatform(shopCartOrderMerger);
//
//        // 计算订单积分抵扣金额
//        if (orderUseScoreManager != null) {
//            orderUseScoreManager.orderUseScore(shopCartOrderMerger, orderParam, shopCartItems);
//        }

        shopCartOrderMerger.setOrderShopReduce(orderShopReduce);
        // 缓存计算
        confirmOrderManager.cacheCalculatedInfo(userId, shopCartOrderMerger);
        return ServerResponseEntity.success(shopCartOrderMerger);
    }

//    /**
//     * 立即购买  提交积分订单
//     */
//    @PostMapping("/submit")
//    @Operation(summary =  "提交订单，返回支付流水号", description = "提交积分订单，用户开始进行支付")
//    public ServerResponseEntity<OrderNumbersDto> submitOrders(@Valid @RequestBody OrderShopParam orderShopParam) {
//        String userId = SecurityUtils.getUser().getUserId();
//
//        // 防止重复、同时提交
//        boolean cad = RedisUtil.cad(OrderCacheNames.SCORE_ORDER_CONFIRM_UUID_KEY + OrderCacheNames.UNION  + userId, userId);
//        System.out.println(" is cad " + cad);
//        if (!cad) {
//            // 订单状态已经发生改变，请重新下单
//            throw new YamiShopBindException("yami.order.status.check.change");
//        }
//
//        // 看看订单的标记有没有过期
//        if (cacheManagerUtil.getCache(OrderCacheNames.SCORE_ORDER_CONFIRM_KEY,  userId) == null) {
//            // 订单已过期，请重新下单
//            throw new YamiShopBindException("yami.order.expired");
//        }
//
//        ScoreOrderMergerDto mergerOrder = cacheManagerUtil.getCache(OrderCacheNames.SCORE_ORDER_CONFIRM_KEY, userId);
//        if (mergerOrder == null) {
//            // 订单已过期，请重新下单
//            throw new YamiShopBindException("yami.order.expired");
//        }
//
//        UserExtension user = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId,userId));
//        if(user.getScore() == null){
//            user.setScore(0);
//        }
//        ProductItemDto productItemDto = mergerOrder.getProductItemDto();
//        if(productItemDto.getScorePrice() > user.getScore()) {
//            // 用户积分不足
//            throw new YamiShopBindException("yami.user.score.enough");
//        }
//        StringBuilder orderNumbers = new StringBuilder();
//        mergerOrder.setRemarks(orderShopParam.getRemarks());
//        Order scoreOrder = scoreOrderService.submit(userId,mergerOrder);
//        orderNumbers.append(scoreOrder.getOrderNumber());
//        // 移除缓存
//        skuService.removeSkuCacheBySkuId(mergerOrder.getProductItemDto().getSkuId(),mergerOrder.getProductItemDto().getProdId());
//        productService.removeProdCacheByProdId(mergerOrder.getProductItemDto().getProdId());
//
//        scoreOrderService.removeConfirmScoreOrderCache(userId);
//        return ServerResponseEntity.success(new OrderNumbersDto(orderNumbers.toString()));
//    }

}
